package jp.sourceforge.akjrcp.text_douga.item;

import java.awt.Font;
import java.awt.FontMetrics;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.util.ArrayList;
import java.util.List;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import jp.sourceforge.akjrcp.text_douga.Messages;


public class TextDougaTextUtils {
	public static Log log=LogFactory.getLog(TextDougaTextUtils.class);
private static BufferedImage bimage=new BufferedImage(1,1,BufferedImage.TYPE_INT_RGB);
//TODO support auto line separate.
public static char splitchars[]={'\n'};//,' ',':',';','.',',',Messages.getString("textdouga.splitcharacter1").charAt(0),Messages.getString("textdouga.splitcharacter2").charAt(0)};//todo �Aor �B
public static String[] wrapText(String line,Font font,int maxwidth){
	return wrapText(line,font,maxwidth,maxwidth);
}
public static String[] wrapText(String line,Font font,int firstMaxWidth,int defaultMaxWidth){
	int maxwidth=firstMaxWidth;
	
	line=line.replaceAll("\r\n", "\n");
	line=line.replaceAll("\r", "\n");
	List<String> textList=new ArrayList<String>();
	Graphics g=bimage.getGraphics();
	g.setFont(font);
	FontMetrics fm=g.getFontMetrics();
	String tmpText[]=splitText(line);
	log.trace("separeted:"+tmpText.length);
	for (int i = 0; i < tmpText.length; i++) {
		log.info("("+tmpText[i]+")");
	}
	String currentLine=null;
	for (int i = 0; i < tmpText.length; i++) {
		
		if(tmpText[i].equals("")){//when line separator
		if(currentLine!=null){
		textList.add(currentLine);
		maxwidth=defaultMaxWidth;
		currentLine=null;
		//add "" if last line is ""
		if(i==tmpText.length-1){
			textList.add("");	//for multiStyledText
			maxwidth=defaultMaxWidth;
			}
		}else{
			textList.add("");
			maxwidth=defaultMaxWidth;
		}
		}else{
		boolean done=false;
		if(currentLine!=null){//trying add line all.
			String tmp=currentLine+tmpText[i];
			if(stringWidth(fm,tmp)>maxwidth){
			textList.add(currentLine);
			maxwidth=defaultMaxWidth;
			}else{
			//width not over plus.
			currentLine+=tmpText[i];
			done=true;
			}
		}
		if(!done){
		String text=tmpText[i];
		String add=""+text.charAt(0);
		
		//for MultiStyledText
		//if on first line,first character already over maxwidth:there no more space on MultiStyledText item
		//auto line separate.
		if(firstMaxWidth!=defaultMaxWidth && maxwidth==firstMaxWidth){
			if(stringWidth(fm,add)>maxwidth){
				textList.add("");	//for multiStyledText
				maxwidth=defaultMaxWidth;
			}
		}
		
		for (int j = 1; j < text.length(); j++) {
				if(stringWidth(fm,add+text.charAt(j))>maxwidth){
					textList.add(add);
					maxwidth=defaultMaxWidth;
					add=""+text.charAt(j);
				}else{
					add=add+text.charAt(j);
				}
			}
		//first character wrap.
		if(add.length()>0){
			currentLine=add;
			}
		}
		}
	}
	
	if(currentLine!=null){
		textList.add(currentLine);
	}
	
	
	g.dispose();
	return textList.toArray(new String[textList.size()]);
}
public static int stringWidth(Font font,String text){
	Graphics g=bimage.getGraphics();
	g.setFont(font);
	FontMetrics fm=g.getFontMetrics();
	int value=fm.stringWidth(text);;
	log.trace(value+"px:"+text);
	g.dispose();
	return value;
}

private static int stringWidth(FontMetrics fm,String text){
	int value=fm.stringWidth(text);;
	log.trace(value+"px:"+text);
	return value;
}

/**
 * split text \n is split as empty text.
 * @param text
 * @return
 */
private static String[] splitText(String text){
    List<String> list=new ArrayList<String>();
    StringBuffer buffer=new StringBuffer();
    for(int i=0;i<text.length();i++){
        char ch=text.charAt(i);
        boolean isSplit=false;
        for(int j=0;j<splitchars.length;j++){
           
            if(ch==splitchars[j]){
                isSplit=true;
                break;
            }
            
        }
        if(isSplit){
           // if(buffer.length()>0){
            	if(ch=='\n'){
            		if(buffer.length()>0){
            			list.add(buffer.toString());
            		}
            		list.add("");
            	}else{
            		list.add(buffer.toString()+ch);
            	}
                buffer=new StringBuffer();
            //}else{
            //    list.add(""+ch);
           // }
            
        
        }else{
                buffer.append(ch);
            }
    }
    if(buffer.length()>0){
        list.add(buffer.toString());
    }
   
    return (String[]) list.toArray(new String[list.size()]);
}
}
